/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateSinistroDialog.java
 *
 * Created on 23/11/2011, 16:45:47
 */
package br.com.seguradora.view.dialog;

import br.com.seguradora.exception.InputValidationException;
import br.com.seguradora.exception.PersistenciaException;
import br.com.seguradora.model.Sinistro;
import br.com.seguradora.model.Veiculo;
import br.com.seguradora.service.SinistroService;
import br.com.seguradora.view.ErrorsList;
import br.com.seguradora.view.StateEntityWindow;
import br.com.seguradora.view.UserError;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import um.filteredtext.number.CurrencyNumberAdapter;

/**
 *
 * @author Diego
 */
public class CreateSinistroDialog extends javax.swing.JDialog {
    
    private Sinistro sinistro;
    private Veiculo veiculo;
    private final static String titleWindow = "Sinistro";
    private StateEntityWindow stateEntity;
    private CurrencyNumberAdapter valorPrejuizoFormat;    
    
    public CreateSinistroDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Sinistro sinistro) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setSinistro(sinistro);
        organizeWindow();
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        codigoLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        codigoVeiculoField = new javax.swing.JTextField();
        veiculoField = new javax.swing.JTextField();
        abrirVeiculosButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        codigoAssociadoField = new javax.swing.JTextField();
        associadoField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel5 = new javax.swing.JLabel();
        valorPrejuizoField = new javax.swing.JTextField();
        fotosAnexasPanel = new br.com.seguradora.view.panel.FotosEmAnexoPanel();
        veiculoErrorLabel = new javax.swing.JLabel();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        dataField = new org.jdesktop.swingx.JXDatePicker();
        jSeparator3 = new javax.swing.JSeparator();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        observacaoField = new javax.swing.JTextArea();
        valorErrorLabel = new javax.swing.JLabel();
        dataErrorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Código:");

        codigoLabel.setText("0");

        jLabel3.setText("Veículo:");

        codigoVeiculoField.setEditable(false);
        codigoVeiculoField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        codigoVeiculoField.setFocusable(false);

        veiculoField.setEditable(false);
        veiculoField.setFocusable(false);

        abrirVeiculosButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/magnifier.png"))); // NOI18N
        abrirVeiculosButton.setToolTipText("Abrir pesquisa de veículos");
        abrirVeiculosButton.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        abrirVeiculosButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirVeiculosButtonActionPerformed(evt);
            }
        });

        jLabel4.setText("Associado:");

        codigoAssociadoField.setEditable(false);
        codigoAssociadoField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        codigoAssociadoField.setFocusable(false);

        associadoField.setEditable(false);
        associadoField.setFocusable(false);

        jLabel5.setText("Valor Prejuízo:");

        veiculoErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Data:");

        jLabel6.setText("Observações:");

        observacaoField.setColumns(20);
        observacaoField.setLineWrap(true);
        observacaoField.setRows(5);
        observacaoField.setWrapStyleWord(true);
        jScrollPane1.setViewportView(observacaoField);

        valorErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        dataErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
            .addComponent(fotosAnexasPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(codigoLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(codigoAssociadoField, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(associadoField))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(codigoVeiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(veiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(abrirVeiculosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(veiculoErrorLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(valorPrejuizoField, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(valorErrorLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dataField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dataErrorLabel)))
                .addContainerGap(173, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(111, 111, 111)
                        .addComponent(confirmarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 518, Short.MAX_VALUE))
                    .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE))
                .addContainerGap())
            .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 663, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(54, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(codigoLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(dataField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dataErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(abrirVeiculosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(codigoVeiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(veiculoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(codigoAssociadoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(associadoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(valorErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel5)
                                .addComponent(valorPrejuizoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(veiculoErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fotosAnexasPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelarButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void abrirVeiculosButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_abrirVeiculosButtonActionPerformed
        ConsultaVeiculoDialog dialog = new ConsultaVeiculoDialog(new javax.swing.JFrame(), true, StateEntityWindow.SEARCH);
        dialog.setSelectEntity(true);
        dialog.setVisible(true);
        Veiculo veiculo = dialog.getVeiculo();
        setVeiculo(veiculo);
}//GEN-LAST:event_abrirVeiculosButtonActionPerformed
    
    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            SinistroService sinistroService = new SinistroService();
            Sinistro sinistro = getSinistro();
            if (getStateEntity() == StateEntityWindow.NEW) {
                sinistroService.inserir(sinistro);
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
}//GEN-LAST:event_confirmarButtonActionPerformed
    
    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
}//GEN-LAST:event_cancelarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                CreateSinistroDialog dialog = new CreateSinistroDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton abrirVeiculosButton;
    private javax.swing.JTextField associadoField;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField codigoAssociadoField;
    private javax.swing.JLabel codigoLabel;
    private javax.swing.JTextField codigoVeiculoField;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel dataErrorLabel;
    private org.jdesktop.swingx.JXDatePicker dataField;
    private br.com.seguradora.view.panel.FotosEmAnexoPanel fotosAnexasPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTextArea observacaoField;
    private javax.swing.JLabel valorErrorLabel;
    private javax.swing.JTextField valorPrejuizoField;
    private javax.swing.JLabel veiculoErrorLabel;
    private javax.swing.JTextField veiculoField;
    // End of variables declaration//GEN-END:variables

    private void organizeWindow() {
        isShowErrorsLabel(false);
        configTextFieldsDeDinheiro();
        if(getStateEntity() == StateEntityWindow.NEW) {
            dataField.setDate(new Date());
        }
    }
    
    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }
    
    private void setSinistro(Sinistro sinistro) {
        if (sinistro == null) {
            return;
        }
        this.sinistro = sinistro;
    }
    
    private Sinistro getSinistro() {
        if (sinistro == null) {
            sinistro = new Sinistro();
        }        
        try {
            sinistro.setData(dataField.getDate());
            sinistro.setVeiculo(getVeiculo());
            sinistro.setFotosList(fotosAnexasPanel.getFotosList());
            sinistro.setObservacao(observacaoField.getText());
            Number valor = valorPrejuizoFormat.getNumberFormat().parseNumber(valorPrejuizoField.getText());
            sinistro.setValorPrejuizo(Double.valueOf(valor.toString()));
        } catch (ParseException ex) {
            sinistro.setValorPrejuizo(0d);
            System.out.println(ex.getMessage());
        }
        
        return sinistro;
    }
    
    private void setVeiculo(Veiculo veiculo) {
        if (veiculo != null) {
            this.veiculo = veiculo;
            codigoVeiculoField.setText(String.valueOf(veiculo.getId()));
            veiculoField.setText(veiculo.toString());
            codigoAssociadoField.setText(String.valueOf(veiculo.getAssociado().getId()));
            associadoField.setText(veiculo.getAssociado().getNome());
        }
    }
    
    public Veiculo getVeiculo() {
        return veiculo;
    }
    
    private void configTextFieldsDeDinheiro() {
        valorPrejuizoFormat = new CurrencyNumberAdapter(false);
        valorPrejuizoField.addKeyListener(valorPrejuizoFormat);
        valorPrejuizoField.addFocusListener(valorPrejuizoFormat);
    }
    
    private void isShowErrorsLabel(boolean show) {
        dataErrorLabel.setVisible(show);
        veiculoErrorLabel.setVisible(show);
        valorErrorLabel.setVisible(show);
    }
    
    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }
    
    public Sinistro objetoSinistro() {
        return sinistro;
    }
    
    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if(dataField.getDate() == null) {
            errorsList.addError(new UserError(dataErrorLabel, "O data do sinistro não foi informada."));
        }
        if (codigoVeiculoField.getText().isEmpty()) {
            errorsList.addError(new UserError(veiculoErrorLabel, "O veículo do sinistro não foi informado."));
        }
        if(valorPrejuizoField.getText().isEmpty()) {
            errorsList.addError(new UserError(valorErrorLabel, "O valor do prejuízo não foi informado."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
